// blog 模块
const {getList, getDetail, newBlog, updateBlog, delBlog} = require('../controller/blog');
const {SuccessModel, ErrorModel} = require('../model/resBaseModel');

const handleBlogRouter = (req, res) => {
    const method = req.method;
    const url = req.url;
    const id = req.query.id;

    if (method === 'GET' && req.path === '/api/blog/list') {
        // 获取博客列表
        const author = req.query.author || '';
        const keyword = req.query.keyword || '';
        const result = getList(author, keyword); // 返回promise
        return result.then(listData => {
            return new SuccessModel(listData);   
        })
    }

    if (method === 'GET' && req.path === '/api/blog/detail') {
        // 获取博客详情
        const result = getDetail(id);
        return result.then(data => {
            return new SuccessModel(data);
        });
    }

    if (method === 'POST' && req.path === '/api/blog/new') {
        const loginCheckResult = loginCheck(req);
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult;
        }
        // 新建一篇博客
        req.body.author = req.session.username;
        const result = newBlog(req.body);
        return result.then(data => {
            return new SuccessModel(data);
        })
    }

    if (method === 'POST' && req.path === '/api/blog/update') {
        // 更新一篇博客
        const loginCheckResult = loginCheck(req);
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult;
        }

        const result = updateBlog(id, req.body);
        return result.then(val => {
            if (val) {
                return new SuccessModel("更新博客成功");
            }
            return new ErrorModel('更新博客失败');
        })
    }

    if (method === 'POST' && req.path === '/api/blog/delete') {
        // 删除一篇博客
        const loginCheckResult = loginCheck(req);
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult;
        }

        const author = req.session.username;
        const result = delBlog(id, author);
        return result.then(data => {
            if (data) {
                return new SuccessModel("删除博客成功");
            }
            return new ErrorModel('删除博客失败');
        })
    }
}

// 登录验证 新增，删除需要判断是否登录
const loginCheck = (req) => {
    if (!req.session.username) {
        return Promise.resolve(
            new ErrorModel('尚未登录')
        )
    }
}

module.exports = handleBlogRouter